package cn.wyd.shield.authentication;

import cn.wyd.shield.authentication.exception.AuthenticationException;
import cn.wyd.shield.cache.AuthRoleMapper;
import cn.wyd.shield.entity.AuthRole;
import cn.wyd.shield.entity.AuthRolePower;
import cn.wyd.shield.entity.AuthUser;
import cn.wyd.shield.http.support.Url;
import cn.wyd.shield.token.jwt.JwtToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Component
public class UserAuthorization {
    @Autowired
    private AuthRoleMapper authRoleMapper;
    private List<AuthRole> listAuth;
    public   void  userAuthorization(Url url, JwtToken jwtToken){
        listAuth = loadUserAuth(jwtToken.getUid());
        if(!checkUserAuth(url,listAuth)){
            throw  new AuthenticationException("用户无权限");
        }
    }
    public List<AuthRole> loadUserAuth(String uId){
        return   authRoleMapper.loadUserAuth(uId);
    }
    private Boolean checkUserAuth(Url url,List<AuthRole> listAuth){
        String role = url.getRole();
        String permissions = url.getPermissions();
        for (AuthRole item : listAuth) {
            if(item.getName().equals(role)){
                for(AuthRolePower power: item.getAuthRolePowers() ) {
                    if(power.getName().equals(permissions)){
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
